package org.atf.model.dao;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.atf.model.entity.DpService;
import org.atf.model.entity.JobSummary;
import org.atf.model.entity.Jobs;
import org.atf.model.entity.Preference;
import org.atf.model.entity.Profile;
import org.atf.model.entity.Server;
import org.atf.model.utils.EntityManagerUtil;


public class AtfSchedulerDAO {
	private static Logger logger = Logger.getLogger(AtfSchedulerDAO.class);
	
	public List<String> getUniqueRegions(){
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		Query query = entityManager.createQuery("select distinct j.region from Jobs j");
		List<String> resultList = query.getResultList();
		return resultList;
		
	}
	
	public List<Jobs> getSchedulersByRegion(String regionName){
		EntityManager entityManager=EntityManagerUtil.getEntityManager();
		Query query = entityManager.createQuery("select j from Jobs j where j.region='"+regionName+"'");
		List<Jobs> resultList = query.getResultList();
		return resultList;
	}
	
	public Jobs getJobsId(Integer id) {
		// TODO Auto-generated method stub
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		Jobs jobs=entityManager.find(Jobs.class, id);
	 	return jobs;
	}

	public boolean updateScheduleStatus(Integer scheduleId, String status) {
		
		// TODO Auto-generated method stub
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		try{
			entityManager.getTransaction().begin();
			String sql="UPDATE Jobs j SET j.status = '"+status+"' WHERE j.jobId = "+scheduleId;
			Query query= entityManager.createQuery(sql);
			int rowCount = query.executeUpdate();
			entityManager.getTransaction().commit();
			if(rowCount >0){
				return true;
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}

	public void addSchedulerJob(Jobs job) {
		// TODO Auto-generated method stub
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		entityManager.getTransaction().begin();
		entityManager.persist(job);
		entityManager.getTransaction().commit();	
	}

	public void updateSchedulerJob(Jobs job) {
		// TODO Auto-generated method stub
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		try{
			entityManager.getTransaction().begin();
			entityManager.merge(job);
			entityManager.getTransaction().commit();
		}finally {
		//	entityManager.close();
		}
	}
	
	public void addSchedulerJobSummary(JobSummary jobSummary){
		 EntityManager entityManager = EntityManagerUtil.getEntityManager();
		 entityManager.getTransaction().begin();
		 entityManager.persist(jobSummary);
		 entityManager.getTransaction().commit();
			 
	}

	public void deleteSchedulerJob(Integer jobId) {
		// TODO Auto-generated method stub
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		entityManager.getTransaction().begin();
		Jobs jobs=entityManager.find(Jobs.class, jobId);
		Query q = entityManager.createQuery("DELETE FROM JobSummary js WHERE js.jobId = :jobId and js.jobName = :jobName and js.region = :region");
		q.setParameter("jobId", jobs.getJobId());	
		q.setParameter("jobName", jobs.getName());	
		q.setParameter("region", jobs.getRegion());
		int deleted = q.executeUpdate();
		entityManager.remove(jobs);
		entityManager.getTransaction().commit();
		
	}

	public void updateJobLastRun(Integer jobId, Date time) {
		// TODO Auto-generated method stub
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		
		entityManager.getTransaction().begin();
		
		Jobs jobs=entityManager.find(Jobs.class, jobId);
		jobs.setLastRun(time);
		entityManager.merge(jobs);
		entityManager.getTransaction().commit();
		
	}

	public void updateJobNextRun(Integer jobId, Date nextFireTime) {
		// TODO Auto-generated method stub
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		
		entityManager.getTransaction().begin();
		Jobs jobs=entityManager.find(Jobs.class, jobId);
		jobs.setNextRun(nextFireTime);
		entityManager.merge(jobs);
		entityManager.getTransaction().commit();
	}

	public List<Preference> getPreference(Integer jobId) {
		// TODO Auto-generated method stub
		//EntityManager entityManager = EntityManagerUtil.getEntityManager();
		List<Preference> prefList = new ArrayList<Preference>();
		try{
			prefList.addAll(getJobsId(jobId).getPreference());
		}finally {
			//entityManager.close();
		}
		return prefList;
	}
	public void insertPreference(Integer jobId, Preference preference) {
		// TODO Auto-generated method stub
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		 try{
			 entityManager.getTransaction().begin();
			 entityManager.persist(preference);
			 Jobs jobs=entityManager.find(Jobs.class, jobId);
			 jobs.addPreference(preference);
			 entityManager.merge(jobs);
			 entityManager.getTransaction().commit();
			 
		 }finally {
			// entityManager.close();
		 }	
	}

	public void deletePreference(Integer jobId, Integer prefId) {
		// TODO Auto-generated method stub
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		
		 try{
				entityManager.getTransaction().begin();
				Jobs jobs=entityManager.find(Jobs.class, jobId);
				Preference pref = null;
				for(Preference preference : jobs.getPreference()) {
					if(preference.getId() == prefId){
						pref= preference;
						//entityManager.remove(preference);
					}
				}
				if(pref != null){
					jobs.removePreference(pref);
				}
				entityManager.remove(pref);
				entityManager.merge(jobs);
				entityManager.getTransaction().commit();
				
				
		 } finally {
			// entityManager.close();
		 }	
	}

	public void updateWebSchedulerJob(Jobs job) {
		// TODO Auto-generated method stub
		// this Method will be used when Parent(Job) is updated via Web without update/deleting the child
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		entityManager.getTransaction().begin();
		logger.debug("Updating...Jobs: "+job);
		Jobs cjobs=entityManager.find(Jobs.class, job.getJobId());
		logger.debug("Current...Job: "+cjobs);
		cjobs.updateProperties(job);
		logger.debug("New Update...Job: "+cjobs);
		entityManager.merge(cjobs);
		entityManager.getTransaction().commit();
		
	}

	public List<JobSummary> getJobSummaryDetails(Integer jobId, String jobName,
			String jobRegion, Date cDate) {
		// TODO Auto-generated method stub
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		logger.debug("jobId: "+jobId);
		logger.debug("jobName: "+jobName);
		logger.debug("jobRegion: "+jobRegion);
		logger.debug("cDate: "+cDate);
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		Calendar sCalender= Calendar.getInstance();
		sCalender.setTime(cDate);
		logger.debug("sCalender: "+sCalender.getTime());
		Calendar eCalender= Calendar.getInstance();
		eCalender.setTime(cDate);
		eCalender.add(Calendar.DAY_OF_MONTH, 1);
		logger.debug("eCalender: "+eCalender.getTime());
		//
		//Query query = entityManager.createNativeQuery("select * from JOBSUMMARY WHERE jobId = ?1 and jobName = ?2 and region = ?3 and startDate between ?4 and ?5");
		//Query query = entityManager.createNativeQuery("select * from JOBSUMMARY WHERE jobId = ?1 and startDate between ?2 and ?3");
		//query.setParameter(1, jobId);	
	//	query.setParameter(2, jobName);	
	//	query.setParameter(3, jobRegion);
	///	logger.debug("sFormate: "+formatter.format(sCalender.getTime()));
		//logger.debug("eFormate: "+formatter.format(eCalender.getTime()));
	//	query.setParameter(2, formatter.format(sCalender.getTime()));
	//	query.setParameter(3, formatter.format(eCalender.getTime()));
		
		Query query = entityManager.createQuery("select js from JobSummary js where js.jobId= :jobId and js.jobName = :jobName and js.region= :region and js.startDate between :sDate and :eDate");
		query.setParameter("jobId", jobId);
		query.setParameter("jobName", jobName);
		query.setParameter("region", jobRegion);
		query.setParameter("sDate", sCalender.getTime());
		query.setParameter("eDate", eCalender.getTime());
		System.out.println(query.toString());
		List<JobSummary> resultList = query.getResultList();
		return resultList;
	}

	public boolean updateScheduleCStatus(Integer scheduleId, String cstatus) {
		// TODO Auto-generated method stub
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		try{
			entityManager.getTransaction().begin();
			String sql="UPDATE Jobs j SET j.cStatus = '"+cstatus+"' WHERE j.jobId = "+scheduleId;
			Query query= entityManager.createQuery(sql);
			int rowCount = query.executeUpdate();
			entityManager.getTransaction().commit();
			if(rowCount >0){
				return true;
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
}
